/*
 * MI_TinyFSM - Multi Instansce tinyfsm
 *
 * Salute to tinyfsm https://github.com/digint/tinyfsm
 *
 * Copyright (c) 2023-2024 yuping.li
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#ifndef MI_TINYFSM_H
#define MI_TINYFSM_H

#include <functional>
#include <map>
#include <string>


class MiTinyfsm {
public:
    struct State {
        std::string name;
        std::function<void()> entry;
        std::function<void()> exit;
        std::map<std::string, std::function<void()>> events;
    };

    explicit MiTinyfsm(State &initial_state) : current_state_ptr(&initial_state) { }

    virtual void enter_initial_state() const {
        if (current_state_ptr->entry) {
            current_state_ptr->entry();
        }
    }

    virtual void start() {
        enter_initial_state();
    }

    virtual void dispatch(const std::string& event) {
        if (current_state_ptr->events.count(event)) {
            current_state_ptr->events[event]();
        }
    }

protected:
    virtual void transit(State& state) {
        if (current_state_ptr->exit) {
            current_state_ptr->exit();
        }
        current_state_ptr = &state;
        if (current_state_ptr->entry) {
            current_state_ptr->entry();
        }
    }

    virtual void transit(State& state, const std::function<void()>& action) {
        if (current_state_ptr->exit) {
            current_state_ptr->exit();
        }
        action();
        current_state_ptr = &state;
        if (current_state_ptr->entry) {
            current_state_ptr->entry();
        }
    }

    virtual void transit(State& state, const std::function<void()>& action, const std::function<bool()>& condition) {
        if (condition()) {
            transit(state, action);
        }
    }

    State* current_state_ptr{nullptr};
};

#endif //MI_TINYFSM_H
